#include <stdlib.h>
#include "filereq.h"
#include "amigawindow.h"
#include "amigascreen.h"
#include "textbox.h"
#include "button.h"
#include "rect.h"
#include "stringiterator.h"
#include "filerequester.h"

FileReq::FileReq(AmigaScreen* screen) {
	_screen = screen;
	
	initGUI();
}

void FileReq::initGUI() {
	// Add window
	_window = new AmigaWindow(0, 13, 256, 179, "Output Window", false, true);
	_screen->addGadget(_window);
	
	// Get available area within window
	Rect rect;
	_window->getClientRect(rect);
		
	// Add textbox - this will tell the user that we're waiting for the FAT system to start up
	_textbox = new TextBox(rect.x, rect.y, rect.width, rect.height, "Initialising FAT...");
	_textbox->setTextAlignmentVert(TextBox::TEXT_ALIGNMENT_VERT_TOP);
	_window->addGadget(_textbox);

	// Attempt to initialise the FAT system
#ifdef USING_LIBELM
	if (ELM_Mount()) {
#else
	if (fatInitDefault()) {
#endif
		// FAT initialisation worked!  Update the textbox to tell the user that all is OK
		_textbox->setText("FAT initialised");
			
		// Create file requester at the root of the file system
		FileRequester* req = new FileRequester(10, 10, 200, 180, "Files", "/");
		req->setRefcon(1);
		req->addGadgetEventHandler(this);
		_screen->addGadget(req);
	} else {
		
		// FAT initialisation failed!  Update textbox to tell user that we're stuck
		_textbox->setText("Failed to initialise FAT");
	}
}

void FileReq::handleValueChangeEvent(const GadgetEventArgs& e) {

	// Did a gadget fire this event?
	if (e.getSource() != NULL) {
		
		// Is the gadget the file requester?
		if (e.getSource()->getRefcon() == 1) {
			
			// Update the textbox with the name of the requested file
			const ListDataItem* item = ((FileRequester*)e.getSource())->getSelectedOption();
						
			if (item != NULL) {
				_textbox->setText(item->getText());
			}else{
				_textbox->setText(((FileRequester*)e.getSource())->getTextBoxFileName());
			}
		}
	}
}
